//
//  HomeViewController.m
//  Arts1
//
//  Created by Mac Jc on 15/10/21.
//  Copyright © 2015年 Arts1. All rights reserved.
//

#import "HomeViewController.h"
#import "CHTCollectionViewWaterfallLayout.h"
#import "HomeWaterFlowCell.h"
//#import "HomeCollectionCell.h"
#import "HomeCollectionHeaderView.h"
#import "HomeCollectionFooterView.h"
#import "HomeDetialViewController.h"
#import "AllHeader.h"
#import "HomeListModel.h"

//  长按手势
#import "GHContextMenuView.h"
#import "UserLongGestureController.h"


#define CELL_IDENTIFIER @"WaterfallCell"
#define HEADER_IDENTIFIER @"WaterfallHeader"
#define FOOTER_IDENTIFIER @"WaterfallFooter"


#define kURL @"http://arts1.cn/app/getphotolist"

typedef NS_ENUM(NSInteger, RefreshType) {
    RefreshTypeNew,
    RefreshTypeMore
};

@interface HomeViewController ()<UICollectionViewDataSource, CHTCollectionViewDelegateWaterfallLayout,UICollectionViewDelegate,GHContextOverlayViewDataSource, GHContextOverlayViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;

//获取数据源
@property (nonatomic ,strong) NSMutableArray *dataSource;

//  保存当前状态 上拉加载  下拉刷新
@property (nonatomic, assign) RefreshType refreshType;

//  添加长按手势
@property (nonatomic ,strong) UserLongGestureController *longGestureVC;
@property (nonatomic, strong) UIButton *removeAddPhotoViewButton;

@property (nonatomic ,strong) NSString *pageNumber;


@end




@implementation HomeViewController


//懒加载
- (NSMutableArray *)dataSource{
    if (_dataSource == nil)
    {
        self.dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

#pragma mark - Life Cycle

- (void)dealloc {
    _collectionView.delegate = nil;
    _collectionView.dataSource = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.hidden = YES;
    self.view.backgroundColor = kBackgroundColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    [self requestData:@"1"];
    
    [self creactCollectionView];
    
    // 长按手势button
//    GHContextMenuView* overlay = [[GHContextMenuView alloc] init];
//    overlay.dataSource = self;
//    overlay.delegate = self;
//    UILongPressGestureRecognizer* _longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:overlay action:@selector(longPressDetected:)];
//    [self.view setUserInteractionEnabled:YES];
//    [self.view addGestureRecognizer:_longPressRecognizer];
    
    UILongPressGestureRecognizer* _longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(getPicture:)];
    [self.view setUserInteractionEnabled:YES];
    [self.view addGestureRecognizer:_longPressRecognizer];

    
    __weak HomeViewController *productVC = self;
    [self.collectionView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        _refreshType = RefreshTypeNew;
        [productVC requestData:@"1"];
    }];
    
    [self.collectionView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        _refreshType = RefreshTypeMore;
        [productVC requestData:productVC.pageNumber];
    }];
    
    // 提取当前用户的登陆状态
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    NSInteger loginStatius = [dic[@"status"] integerValue];
    
    // 当提取到的用户登陆状态为1时，不再添加登陆页面，否则添加登陆界面
    if(loginStatius != 1)
    {
        [self createLoginView];
    }
    else
    {
        self.tabBarController.tabBar.hidden = NO;
    }
    
}





#pragma mark - 创建登陆页面
- (void)createLoginView{
    
    LoginBasicViewController *loginBVC = [[LoginBasicViewController alloc] init];
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:loginBVC];
    self.tabBarController.tabBar.hidden = YES;
    
    loginBVC.showbarblock = ^(){
        // 登陆成功后，显示tabbar ，将登陆界面移除，显示主页面
        self.tabBarController.tabBar.hidden = NO;
        [navi.view removeFromSuperview];
    };
    [self.view addSubview:navi.view];
    
    
}

#pragma mark - 请求数据
- (void)requestData:(NSString *)page
{
    
    _pageNumber = page;
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    if (_refreshType == RefreshTypeMore) {
        
    }
    NSMutableDictionary *pardic = [NSMutableDictionary dictionary];
    if (_pageNumber) {
        [pardic setObject:_pageNumber forKey:@"page"];

    }
    
    [manage GET:kURL parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
//             NSLog(@"%@",dic);
             if (_refreshType == RefreshTypeNew) {
                 [self.dataSource removeAllObjects];
             }
             
             int status = [dic[@"status"] intValue];
             //获取当前页
             int curPage = [dic[@"curPage"] intValue];
             curPage++;
             //存储当前页
             self.pageNumber = [NSString stringWithFormat:@"%d",curPage];
             
//             [self.dataSource removeAllObjects];
             if (responseObject)
             {
                 if (status == 1)//状态为1的时候请求成功
                 {
                     NSArray *array = dic[@"list"];
                     
                     for (NSDictionary *dict in array)
                     {
                         HomeListModel *model = [[HomeListModel alloc] init];
                         [model setValuesForKeysWithDictionary:dict];
                         [self.dataSource addObject:model];
                     }
                 }
             }
             [self.collectionView reloadData];
             [self.collectionView.defaultHeader endRefreshing];
             [self.collectionView.defaultFooter endRefreshing];
             
             // 请求成功的时候调用这个block
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];
}



#pragma mark -- 瀑布流自带方法
//- (void)viewDidAppear:(BOOL)animated {
//    [super viewDidAppear:animated];
//    [self updateLayoutForOrientation:[UIApplication sharedApplication].statusBarOrientation];
//}

//- (void)updateLayoutForOrientation:(UIInterfaceOrientation)orientation {
//    CHTCollectionViewWaterfallLayout *layout =
//    (CHTCollectionViewWaterfallLayout *)self.collectionView.collectionViewLayout;
//    layout.columnCount = UIInterfaceOrientationIsPortrait(orientation) ? 2 : 3;
//}

//- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
//    [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
//    [self updateLayoutForOrientation:toInterfaceOrientation];
//}

//- (UICollectionView *)collectionView {
- (void)creactCollectionView
{
//    if (!_collectionView) {
        CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
        
        layout.sectionInset = UIEdgeInsetsMake(0, 10, 59, 10);
        layout.headerHeight = 0;
        layout.footerHeight = 10;
        layout.minimumColumnSpacing = 10;
        layout.minimumInteritemSpacing = 10;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 20 * HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT) collectionViewLayout:layout];
        _collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = kBackgroundColor;
        [_collectionView registerClass:[HomeWaterFlowCell class]
            forCellWithReuseIdentifier:CELL_IDENTIFIER];
        [_collectionView registerClass:[HomeCollectionHeaderView class]
            forSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader
                   withReuseIdentifier:HEADER_IDENTIFIER];
        [_collectionView registerClass:[HomeCollectionFooterView class]
            forSupplementaryViewOfKind:CHTCollectionElementKindSectionFooter
                   withReuseIdentifier:FOOTER_IDENTIFIER];
    [self.view addSubview:self.collectionView];
//    }
}
//    return _collectionView;
//}



#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
//    return CELL_COUNT;
    return self.dataSource.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HomeWaterFlowCell *cell =
    (HomeWaterFlowCell *)[collectionView dequeueReusableCellWithReuseIdentifier:CELL_IDENTIFIER
                                                                                forIndexPath:indexPath];
    HomeListModel *model = _dataSource[indexPath.row];
    cell.model = model;
    cell.layer.masksToBounds = YES;
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *reusableView = nil;
    
    if ([kind isEqualToString:CHTCollectionElementKindSectionHeader]) {
        reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                          withReuseIdentifier:HEADER_IDENTIFIER
                                                                 forIndexPath:indexPath];
    } else if ([kind isEqualToString:CHTCollectionElementKindSectionFooter]) {
        reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                          withReuseIdentifier:FOOTER_IDENTIFIER
                                                                 forIndexPath:indexPath];
    }
    
    return reusableView;
}


#pragma mark - CHTCollectionViewDelegateWaterfallLayout
//  设置item高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    HomeListModel *model = _dataSource[indexPath.row];
    CGFloat itemHeight = [HomeWaterFlowCell heightOfCell:model];
    CGSize itemSize = CGSizeMake((SCREEN_WIDTH - 30) / 2 , itemHeight);
    return itemSize;
}


#pragma mark - CHTCollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    HomeListModel *model = _dataSource[indexPath.row];
    HomeDetialViewController *homeDetialVC = [[HomeDetialViewController alloc] init];
    homeDetialVC.imageID = model.Id;
    homeDetialVC.userId = model.userId;
    homeDetialVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:homeDetialVC animated:YES];
    homeDetialVC.hidesBottomBarWhenPushed = NO;
    
    
}



#pragma mark --长按手势代理

- (NSInteger) numberOfMenuItems{
    return 0;
}

-(UIImage*) imageForItemAtIndex:(NSInteger)index{
    NSString* imageName = nil;
    imageName = @"CollectionButton";
//    switch (index) {
//        case 0:
//            imageName = @"CollectionButton";
//            break;
//        case 1:
//            imageName = @"TabGood";
//            break;
//        case 2:
//            imageName = @"shareBigButton";
//        default:
//            break;
//    }
    return [UIImage imageNamed:imageName];
}

- (void) didSelectItemAtIndex:(NSInteger)selectedIndex forMenuAtPoint:(CGPoint)point{
    //    NSString* msg = nil;
//    switch (selectedIndex) {
//        case 0:
//            //            msg = @"加好友";
//            break;
//        case 1:
//            //            msg = @"d点赞";
////            [self tapGood];
//            break;
//        case 2:
//            //            msg = @"分享";
////            [self share];
//            break;
//        default:
//            break;
//    }
    
    _longGestureVC = [[UserLongGestureController alloc] init];
    _longGestureVC.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    _longGestureVC.backViewButton.alpha = 0;
    [self.view addSubview:self.longGestureVC.view];
    
    //  添加移除按钮
    _removeAddPhotoViewButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _removeAddPhotoViewButton.frame = CGRectMake(SCREEN_WIDTH / 2.0 - 20, SCREEN_HEIGHT - 100 *HEIGHT, 40, 40);
    _removeAddPhotoViewButton.alpha = 0.3;
    [_removeAddPhotoViewButton setBackgroundImage:[UIImage imageNamed:@"cancelcon"] forState:(UIControlStateNormal)];
    [_removeAddPhotoViewButton addTarget:self action:@selector(removeAddPhotoView) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_removeAddPhotoViewButton];
    
}


- (void)addPhoto{
    _longGestureVC = [[UserLongGestureController alloc] init];
//    _longGestureVC.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
//    [self addChildViewController:_longGestureVC];
//    _longGestureVC.backViewButton.alpha = 0;
    _longGestureVC.backViewButton.hidden = YES;
    [self.view addSubview:self.longGestureVC.view];
    
    //  添加移除按钮
    _removeAddPhotoViewButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _removeAddPhotoViewButton.frame = CGRectMake(SCREEN_WIDTH / 2.0 - 20, SCREEN_HEIGHT - 100 *HEIGHT, 40, 40);
    _removeAddPhotoViewButton.alpha = 0.3;
    [_removeAddPhotoViewButton setBackgroundImage:[UIImage imageNamed:@"cancelcon"] forState:(UIControlStateNormal)];
    [_removeAddPhotoViewButton addTarget:self action:@selector(removeAddPhotoView) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_removeAddPhotoViewButton];
    
}

- (void)getPicture:(UILongPressGestureRecognizer *)getPicture
{
    if (getPicture.state == UIGestureRecognizerStateBegan)
    {
        //实现只有第一个分区才能有长按手势
//        CGPoint point = [getPicture locationInView:self.collectionView];
//        NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
//        if (indexPath.section == 0)
//        {
//            //调用相册或相机页面
//            _changeFrameBlock();
//        }
    }
}

//移除添加图片页面
- (void)removeAddPhotoView
{
    [_longGestureVC.view removeFromSuperview];
    [_longGestureVC removeFromParentViewController];
//    _longGestureVC.backViewButton.alpha = 1;
    [_removeAddPhotoViewButton removeFromSuperview];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = NO;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
